package com.yangrui.app.service.impl;

import com.yangrui.app.entity.Episode;
import com.yangrui.app.entity.PlayRecord;
import com.yangrui.app.entity.Video;
import com.yangrui.app.entity.VideoOrder;
import com.yangrui.app.mapper.EpisodeMapper;
import com.yangrui.app.mapper.PlayRecordMapper;
import com.yangrui.app.mapper.VideoMapper;
import com.yangrui.app.mapper.VideoOrderMapper;
import com.yangrui.app.service.VideoOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VideoOrderServiceImpl implements VideoOrderService {

    @Autowired
    private VideoOrderMapper videoOrderMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private PlayRecordMapper playRecordMapper;
    @Autowired
    private EpisodeMapper episodeMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insert(Integer userId, Integer videoId) {

        if(videoOrderMapper.selectByUserIdAndVideoId(userId, videoId) != null) {
            return -1;
        }
        Video video = videoMapper.selectById(videoId);
        if (video==null) {
            return -2;
        }
        //准备订单
        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setUserId(userId);
        videoOrder.setVideoId(videoId);
        videoOrder.setState(0);
        videoOrder.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        videoOrder.setTotalFee(video.getPrice());
        videoOrder.setVideoImg(video.getCoverImg());
        videoOrder.setVideoTitle(video.getTitle());
        videoOrder.setCreateTime(new Date());

        //查询第一集
        Episode episode = episodeMapper.selectFirstEpisodeByVideoId(videoId);
        if(episode == null) {
            throw new RuntimeException("没有第一集");
        }

        //生成播放记录
        PlayRecord playRecord = new PlayRecord();
        playRecord.setUserId(userId);
        playRecord.setVideoId(videoId);
        playRecord.setCreateTime(new Date());
        playRecord.setCurrentNum(episode.getOrderInVideo());
        playRecord.setEpisodeId(episode.getId());
        if(playRecordMapper.insert(playRecord) !=1) {
            throw new RuntimeException("播放记录插入失败");
        }
        videoOrderMapper.insert(videoOrder);
        return 1;
    }

    @Override
    public List<VideoOrder> selectByUserId(Integer userId) {
        return videoOrderMapper.selectByUserId(userId);
    }
}

